package com.example.abc.websocket;

import com.example.abc.util.JsonUtil;
import com.example.abc.websocket.msg.WsBaseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.security.Principal;

/**
 * Created by Peter on 2018/5/6.
 */
public class MyTextWebsocketHandler extends TextWebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(MyTextWebsocketHandler.class);

    // 接收到消息
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        logger.info("\nWS:::: WebSocket receive a message, sessionId=" + session.getId() + ", message:" + JsonUtil.toJson(message));
    }

    // 连接成功
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("\nWS:::: WebSocket connected, sessionId=" + session.getId());
        Principal principal = session.getPrincipal();
        logger.info(JsonUtil.toJson(principal));
        OnlineUsers.addUser(session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        logger.info("\nWS:::: handleTransportError -- >> session.isOpen:" + session.isOpen());
        if (session.isOpen()) {
            session.close();
        }
        OnlineUsers.removeUser(session);
        logger.info("\nWS:::: handleTransportError --> WebSocket connection manual closed, sessionId=" + session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info("\nWS:::: WebSocket connection closed, sessionId=" + session.getId());
        OnlineUsers.removeUser(session);
    }
}
